package pl.itconsus.business.login;

import java.text.MessageFormat;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.itconsus.business.login.exceptions.UserConfirmationTimeExpiredException;
import pl.itconsus.business.login.exceptions.UserDisabledException;
import pl.itconsus.business.login.exceptions.UserNotVerifiedException;
import pl.itconsus.dao.WebUserDao;
import pl.itconsus.model.entities.WebUser;

@Service
@Transactional
public class LoginManagerBean implements LoginManager {

	private static Logger LOG = Logger.getLogger(LoginManagerBean.class);

	@Resource
	private WebUserDao webUserDao;

	/* (non-Javadoc)
	 * @see pl.itconsus.business.login.LoginManager#loginUser(java.lang.String, java.lang.String)
	 */
	public boolean loginUser(String email, String password) throws UserConfirmationTimeExpiredException ,UserNotVerifiedException,UserDisabledException {
		LOG.debug(MessageFormat.format("Trying to login user : {0}", email));
		WebUser webUser = webUserDao.get(email);
		if (webUser == null || !webUser.getPassword().equals(password)) {
			LOG.debug("User not found or password is not proper");
			return false;
		}
		LOG.debug(MessageFormat.format("User was found with id: {0}",
				webUser.getId()));
		switch (webUser.getUserStatus()) {
		case CONFIRMATION_EXPIRED:
			throw new UserConfirmationTimeExpiredException();

		case NOT_VERIFIED:
			LOG.debug("User is no verified already");
			throw new UserNotVerifiedException();
		case DISABLED:
			LOG.debug("User is disabled");
			throw new UserDisabledException();
		case VERIFIED:
			LOG.debug("User is confirmed and verification succeed");
			return true;
		default:
			LOG.error(MessageFormat.format("Unrecognized User status : {0}",
					webUser.getUserStatus()));
			throw new IllegalStateException("Unrecognized user status");
		}
	}
}
